import { ExclamationCircleOutlined } from '@ant-design/icons';
import { Divider, Input, Popconfirm, Form } from 'antd';
import { connect } from 'dva';
import debounce from 'lodash/debounce';
import moment from 'moment';
import PropTypes from 'prop-types';
import React, { PureComponent } from 'react';

import search from '@/src/assets/busi/workStation/Barra/search.png';
import { ModalC, PrimaryC, TableC } from '@/src/components';
import { PenetrateBasicInfoNamespace } from '@/src/newModels/workStation/PenetrateBasicInfoM';
import { getColumnIntoWidth } from '@/src/utils/utils';

import styles from './index.less';

let inputOnchange; // 标记 虚拟文本
@connect(({ qualificationManagementPlanMaintenanceM, loading, globalM, PenetrateBasicInfoM }) => ({
  qualificationManagementPlanMaintenanceM,
  loading,
  globalM,
  PenetrateBasicInfoM,
}))
class BaseInfoAsset extends PureComponent {
  // props默认值
  static defaultProps = {
    onRef: () => {}, // 本组件的引用
    onChangePage: () => {}, // 新增编辑查看用于抛出显示框架还是弹窗参数
    onHandleTradingCode: () => {}, // 响应证券代码点击
    onFreshAssetsChange: () => {}, // 响应删除数据
  };

  // 穿透工作台基本信息资产Tab
  constructor(props) {
    super(props);
    this.state = {
      productPositionsOpen: false, // 产品持仓modal
      dataSource: [], // 资产-数据
      columns: [], // 资产-列
      numInPage: 10, // 资产-pageSize
      currentPage: 1, // 资产-currentPage
      total: 0, // 资产-total
      sortedInfo: {}, // 排序对象
    };
    this.getInfoDebounce = debounce(this.getInfoDebounce, 500);
  }

  formRef = React.createRef();

  // 获取资产数据
  getAssetInfo = (searchVal) => {
    const obj = {};
    if (this.state.sortedInfo?.order) {
      obj.columnKey = this.state.sortedInfo?.columnKey;
      obj.order = this.state.sortedInfo?.order;
    }
    const payload = {
      currentPage: this.state.currentPage,
      numInPage: this.state.numInPage,
      endDateStart: moment().format('YYYY-MM-DD'), // 筛选条件：到期日大于等于今日。
      endDateEnd: '2099-01-01',
      ...obj,
      value: searchVal || this.formRef.current.getFieldValue('searchVal'),
    };
    if (payload.value === undefined) {
      delete payload.value;
    }
    this.props.dispatch({
      type: 'qualificationManagementPlanMaintenanceM/queryTable',
      payload,
      callback: (type, data) => {
        if (type == 'success') {
          this.setState({
            dataSource: data.dataSource ?? [],
            columns: data.columns ?? [],
            total: data.pageInfo && data.pageInfo.total,
          });
        }
      },
    });
  };

  // 资产-表格页码排序改变调用
  handleTableChangeAssets = (pagination, filter, sorter) => {
    this.setState(
      {
        sortedInfo: sorter,
      },
      () => {
        this.setState(
          {
            currentPage: pagination.current,
            numInPage: pagination.pageSize,
          },
          () => this.getAssetInfo(),
        );
      },
    );
  };

  componentDidMount() {
    this.props.onRef && this.props.onRef(this);
    this.getAssetInfo();
  }

  // 搜索框图标
  rightContent = () => (
    <div className='flotRight'>
      <img src={search} />
    </div>
  );

  // 新增
  handleAdd = () => {
    this.props.onChangePage('2', {
      operateType: 1,
    });
  };

  /**
   * 操作列
   * @param e {React.BaseSyntheticEvent}
   * @param record {*}
   */
  handleOperate = (e, record) => {
    e.preventDefault();
    const { type } = e.target.dataset;
    // 查看
    if (type === '1') {
      this.props.onChangePage('2', {
        operateType: 3,
        id: record.id,
      });
    }
    // 产品持仓
    if (type === '2') {
      this.setState({
        productPositionsOpen: true,
      });
      this.props.dispatch({
        type: `${PenetrateBasicInfoNamespace}/getProductPositionsFn`,
        payload: {
          tradingCode: record?.tradingcode,
        },
      });
    }
    // 编辑
    if (type === '3') {
      this.props.onChangePage('2', {
        operateType: 2,
        id: record.id,
      });
    }
    // 删除
    if (type === '4') {
      this.props.dispatch({
        type: 'qualificationManagementPlanMaintenanceM/deleteOne',
        payload: {
          id: record?.id,
        },
        callback: (t) => {
          if (t == 'success') {
            this.getAssetInfo();
            this.props.onFreshAssetsChange(record?.tradingcode); // 删除后刷新估值解析
          }
        },
      });
    }
  };

  handleClickTradingCode = (event, record) => {
    event.preventDefault();
    this.props.onHandleTradingCode(record?.tradingcode, record?.tradingname, 2);
  };

  // 扩展column
  changeColumns = (columns) => {
    if (columns.length === 0) return [];
    let needColumn = columns.filter(
      (item) => !['tradingname', 'price', 'parTotalValue', 'zjUseHy', 'fixedRate', 'planProperty', 'interestMethod', 'assetTypei'].includes(item.key),
    );
    needColumn = [needColumn[0], needColumn[1], needColumn[3], needColumn[5], needColumn[6], needColumn[2], needColumn[4]];
    needColumn.push({
      title: '操作',
      dataIndex: 'operate',
      key: 'operate',
      width: 190,
      fixed: 'right',
      render: (text, record) => (
        <div>
          <a data-type='1' onClick={(e) => this.handleOperate(e, record)}>
            查看
          </a>
          <a data-type='2' onClick={(e) => this.handleOperate(e, record)}>
            产品持仓
          </a>
          <a data-type='3' onClick={(e) => this.handleOperate(e, record)}>
            编辑
          </a>
          <Popconfirm
            title='确定删除？'
            icon={<ExclamationCircleOutlined />}
            onConfirm={() => this.handleOperate({ target: { dataset: { type: '4' } }, preventDefault: () => {} }, record)}
          >
            <a>删除</a>
          </Popconfirm>
        </div>
      ),
    });
    const { sortedInfo } = this.state;
    needColumn.map((x) => {
      x.align = 'left';
      if (x.key === 'operate') {
        x.align = 'right';
      }
      if (x.key == 'tradingcode' || x.key == 'planCreateDate' || x.key == 'planEndDate' || x.key == 'rateType') {
        x.sorter = true;
        x.sortOrder = sortedInfo?.columnKey === x.key && sortedInfo?.order;
        if (x.key == 'tradingcode') {
          x.render = (text, record) => <a onClick={(event) => this.handleClickTradingCode(event, record)}>{text}</a>;
        }
      }
      if (x.key === 'secuabbr' || x.key === 'manager') {
        if (x.width > 180) {
          x.width = 180;
          x.type = 'maxContent';
        }
      }
      if (x.key == 'assetType') {
        x.width = 150;
        x.render = (t) => this.props.qualificationManagementPlanMaintenanceM?.assetTypeList?.filter((i) => i.value == t)[0]?.title || '--';
      }
      // 利率类型
      if (x.key == 'rateType') {
        x.width = 100;
        x.render = (t) => this.props.qualificationManagementPlanMaintenanceM?.rateTypeList?.filter((i) => i.value == t)[0]?.title || '--';
      }
    });
    return needColumn;
  };

  // 执行父组件获取信息getAssetInfo
  getInfoDebounce = (searchVal) => {
    this.getAssetInfo(searchVal);
  };

  // 改变搜索值
  onChange = (e) => {
    const searchVal = e.target?.value;
    this.getInfoDebounce(searchVal);
  };

  onCancel = () => {
    this.setState({
      productPositionsOpen: false,
    });
  };

  render() {
    const { productPositionsOpen, columns, dataSource, currentPage, total, numInPage } = this.state;
    const {
      PenetrateBasicInfoM: { PositionsColumns, PositionsDataSource },
    } = this.props;
    const widthColumn = getColumnIntoWidth(columns, dataSource); // 自动计算width并插入 - 基础信息column
    const newColumns = this.changeColumns(widthColumn);
    const positionsWidthColumn = getColumnIntoWidth(PositionsColumns, PositionsDataSource); // 自动计算width并插入 - 产品持仓column
    return (
      <div className={styles.baseInfoAssets}>
        <Divider className={styles.divider} />
        <div className={styles.baseInfoAssetsContent}>
          <Form ref={this.formRef}>
            <Form.Item name={'searchVal'}>
              <Input
                allowClear={true}
                onCompositionStart={() => {
                  inputOnchange = true;
                }}
                onChange={(e) => {
                  if (!inputOnchange) {
                    this.onChange && this.onChange(e);
                  }
                }}
                onCompositionEnd={(e) => {
                  inputOnchange = undefined;
                  this.onChange && this.onChange(e);
                }}
                placeholder='请输入资产名称或代码进行模糊搜索'
                suffix={this.rightContent()}
                style={{ width: '208px' }}
              />
            </Form.Item>
          </Form>
          <PrimaryC title='新增' onClick={this.handleAdd} />
        </div>
        <TableC
          columns={newColumns}
          dataSource={dataSource}
          selfScrollY={true}
          rowKey='id'
          size='small'
          current={currentPage}
          total={total}
          pageSize={numInPage}
          onChange={this.handleTableChangeAssets}
          scroll={{ x: 'max-content', y: 300 }}
          loading={this.props.loading.effects[`qualificationManagementPlanMaintenanceM/queryTable`]}
        />
        <ModalC title='持仓结果' visible={productPositionsOpen} maskClosable={false} onCancel={() => this.onCancel()} footer={null} width={683}>
          <div>
            <TableC
              columns={positionsWidthColumn || []}
              dataSource={PositionsDataSource || []}
              hidePage={true}
              selfScrollY={true}
              loading={this.props.loading.effects[`${PenetrateBasicInfoNamespace}/getProductPositionsFn`]}
              rowKey='id'
              scroll={{ x: 'max-content', y: 400 }}
            />
          </div>
        </ModalC>
      </div>
    );
  }
}
BaseInfoAsset.propTypes = {
  onRef: PropTypes.func, // 本组件的引用
  onChangePage: PropTypes.func, // 新增编辑查看用于抛出显示框架还是弹窗参数
  onHandleTradingCode: PropTypes.func, // 响应证券代码点击
  onFreshAssetsChange: PropTypes.func, // 响应删除数据
};
export default BaseInfoAsset;
